package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {
	engine := gin.Default()
	//请求示例 /getUser?userId=20210010001
	engine.GET("/getUser", getUser)
	engine.GET("/getUserV2", getUserV2)
	//engine.GET("/getStudent", GetStudent())
	engine.Run()
}

//请求示例 /getUser?userId=20210010001
func getUser(ctx *gin.Context) {
	//userId := ctx.DefaultQuery("userId", "20210010001")	//默认值
	userId := ctx.Query("userId")	//无默认值
	ctx.String(http.StatusOK, fmt.Sprintf("Hello %s\n", userId))
}

//请求示例 /getUser?userId=20210010001
func getUserV2(ctx *gin.Context) {
	var req GetUserReq
	err := ctx.ShouldBind(&req)	//绑定请求参数到结构体
	if err == nil {
		ctx.String(http.StatusOK, fmt.Sprintf("Hello %s\n", req.UserId))
	} else {
		fmt.Println("error.", err)
		ctx.String(http.StatusOK, "system error")
	}
}

type GetUserReq struct {
	UserId string	`form:"userId" binding:"required"`
}